package com.jp.fm.datacollector;

import java.text.NumberFormat;
import java.util.concurrent.TimeUnit;

import org.apache.commons.lang3.StringUtils;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;

import com.jp.fm.HomeFinanceRunner;
import com.jp.fm.dao.AccountDao;
import com.jp.fm.data.Account;
import com.jp.fm.data.UserAccount;

public class SelKohls extends SelParent {

	private WebDriver driver;

	@Before
	public final void setUp() throws Exception {
		this.driver = new FirefoxDriver();
		this.driver.manage().timeouts()
				.implicitlyWait(AllTests.WAIT_TIME_SECONDS, TimeUnit.SECONDS);
	}

	@Test
	public final void testSelKohls() throws Exception {

		// Lookup username, password and url
		UserAccount uAcct = UserAccount.findByRunClass(this.getClass()
				.getName());
		String url = uAcct.getAttribute(UserAccount.URL);
		String username = uAcct.getUsername();
		String password = uAcct.getPassword();
		String name = uAcct.getName();

		this.driver.get(url);

		driver.findElement(By.id("user")).clear();
		driver.findElement(By.id("user")).sendKeys(username);
		driver.findElement(By.id("pass")).clear();
		driver.findElement(By.id("pass")).sendKeys(password);
		driver.findElement(By.id("loginAction")).click();

		String balanceStr = driver
				.findElement(
						By.xpath("//*[@id=\"_id187\"]/table[2]/tbody/tr/td/table[1]/tbody/tr/td[2]"))
				.getText();
		balanceStr = StringUtils.replace(balanceStr, "$", "").trim();
		Number number = NumberFormat.getInstance().parse(balanceStr);
		Float balance = number.floatValue();

		String creditAvailStr = this.driver
				.findElement(
						By.xpath("//*[@id=\"_id187\"]/table[2]/tbody/tr/td/table[3]/tbody/tr/td[2]"))
				.getText();
		creditAvailStr = StringUtils.replace(creditAvailStr, "$", "").trim();
		number = NumberFormat.getInstance().parse(creditAvailStr);
		Float credit = number.floatValue();

		// Logout
		this.driver.findElement(
				By.xpath("//*[@id=\"id97_menu\"]/table/tbody/tr/td[2]"))
				.click();

		// Update account balance
		Account account = getAccountDao().findByName(name);
		balance *= -1;
		account.setBalance(balance);
		account.setAvailableCredit(credit);
		getAccountDao().writeObject(account);
		System.out.println("Account updated");

		// System.out.println(insertCount + " records inserted");

		HomeFinanceRunner.getCache(AccountDao.CACHE_NAME).removeAll();
		System.out.println("Account< " + account.getName() + "> cache cleared");
	}

	@After
	public final void tearDown() throws Exception {
		this.driver.quit();
	}

}
